
//*****************************************************************************
// Headers
//*****************************************************************************
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/msg.h>
#include <pthread.h>
#include <StrToInt.h>

//*****************************************************************************
// Defines
//*****************************************************************************
#define MAXMSG 2048

void TransMsg( const char *msg );

//*****************************************************************************
// MsgQ
//*****************************************************************************
typedef struct _BOX  
{  
   long type;  
   char szMsg[MAXMSG];  
}Box;

int MsgQRx()
{
   int msgid = msgget((key_t)1024, 0666 | IPC_CREAT);
   Box box;

   while(1)
   {
      msgrcv(msgid, (void*)&box, sizeof(box.szMsg), 0, 0);
      printf("msg from client is [%s]\n", box.szMsg);
      TransMsg( box.szMsg );
   }
   
   msgctl(msgid, IPC_RMID, 0);

   return 0;
}

//*****************************************************************************
// Translate MsgQ
//*****************************************************************************
void TransMsg( const char *msg )
{
   StrToInt m_StrToInt;
   unsigned int ch;
   
   if(strcmp(msg, "Update System") > 0)
   {
      printf("Update System and Reboot now.");
      system("/mnt/postUpdate.sh");
   }
   else if(strcmp(msg, "Play") > 0)
   {
      if(strcmp(msg, "0") > 0)
      {
         printf("Play music in channel 0.\r\n");
      }
   }
   else if(strcmp(msg, "Stop") > 0)
   {
      if(strcmp(msg, "0") > 0)
      {
         printf("Stop playing music in channel 0.\r\n");
      }
   }
}

//*****************************************************************************
// Threads
//*****************************************************************************
// TestThread
void* TestThread(void *arg)
{
   while(1)
   {
      // 15s thread
      usleep(15000000);

      printf("Test Thread\n");
   }
}

//*****************************************************************************
// Main
//*****************************************************************************
int main()
{
   int ret;
   pthread_t threadId;
   
   ret = pthread_create(&threadId, NULL, TestThread, NULL);
   if(ret != 0)
   {
      printf("Create thread failed!\r\n");
   }
   
   MsgQRx();
   
   return 0;
}
